package com.template.app.common.service.parser;


import com.template.app.common.bean.UploadResult;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

@Component
public class ImgParser extends MaterialParser {

	@Override
	public String getFileSize(String fileName, byte[] content, long fileLength) throws Exception {
		if(fileLength > (MAX_IMG)){
			throw new Exception("图像大小不能超过 " + MAX_IMG/1024 + "k");
		}
		return getImageSize(fileName, content);
	}
	
	private String getImageSize(String fileName, byte[] content) throws Exception{
		
		try {
			BufferedImage image = ImageIO.read(new ByteArrayInputStream(content));
			int heigth = image.getHeight();
			int width = image.getWidth();
			return width + MULTIPLIE_SIGN + heigth;
		} catch (IOException e) {
			logger.error("can not get height and width[" + fileName + "]", e);
			throw new Exception("素材高度,宽度获取失败.", e);
		}
	}

	@Override
	public void addToResultList(String originalFileName,
			String parentFileName, byte[] content, long fileLength,
			List<UploadResult> resultList) throws IOException {
		resultList.add(super.wrapMaterialResult(originalFileName, parentFileName, content, fileLength));
	}


}
